/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Library General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor Boston, MA 02110-1301,  USA
 */

/*
 * @version bsp.comoro.Sequence v 1.0.0
 * @author Dr.NP <np@bsgroup.org>
 * @package BS.Play
 *
 * Comoro package sequence handler
 */

package bsp.comoro
{
	import flash.net.Socket;
	import flash.utils.ByteArray;
	
	public class Sequence
	{
		private var curr_seq_id : uint;
		private var last_seq_id : uint;
		private var seq_list : Object;
		
		public function Sequence() : void
		{
			this.curr_seq_id = 0;
			this.last_seq_id = 0;
			this.seq_list = new Object();
			
			return;
		}
		
		public function add(d : ByteArray) : ByteArray
		{
			this.curr_seq_id ++;
			
			var k : String = (this.curr_seq_id).toString(16);
			var r : ByteArray = new ByteArray();
			r.writeUnsignedInt(this.curr_seq_id);
			r.writeBytes(d);
			
			this.seq_list[k] = new Object();
			this.seq_list[k]['v'] = r;
			this.seq_list[k]['s'] = 0;
			
			return r;
		}
		
		public function del(seq_id : uint) : Boolean
		{
			var k : String = seq_id.toString(16);
			
			if (!this.seq_list[k])
			{
				return false;
			}
			
			delete(this.seq_list[k]);
			
			return true;
		}
		
		public function resend(seq_id : uint, s : Socket) : Boolean
		{
			if (!s.connected)
			{
				return false;
			}
			
			var k : String = seq_id.toString(16)
			
			if (!this.seq_list[k])
			{
				return false;
			}
			
			s.writeUnsignedInt(this.seq_list[k]['v'].lenght + 4);
			s.writeBytes(this.seq_list[k]['v']);
			s.flush();
			this.seq_list[k]['s'] = 0;
			
			return true;
		}
		
		public function flush(s : Socket) : uint
		{
			if (!s.connected)
			{
				return 0;
			}
			
			var k : String;
			var ct : uint = 0
			
			for (k in this.seq_list)
			{
				if (this.seq_list[k]['s'])
				{
					s.writeUnsignedInt(this.seq_list[k]['v'].length + 4);
					s.writeBytes(this.seq_list[k]['v']);
					s.flush();
					this.seq_list[k]['s'] = 0;
					
					ct ++;
				}
				
				else
				{
					this.seq_list[k]['s'] = 1;
				}
			}
			
			return ct;
		}
		
		public function empty() : void
		{
			this.seq_list = new Object();
			this.curr_seq_id = 0;
			this.last_seq_id = 0;
			
			return;
		}
		
		public function get rcv_id() : uint
		{
			return this.last_seq_id;
		}
		
		public function set rcv_id(id : uint) : void
		{
			this.last_seq_id = id;
			
			return;
		}
	}
}